package com.abing.permissionsys.limit;

import com.abing.permissionsys.webSocket.WebSocketServer;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 接口限流测试类
 */
@Slf4j
@RestController
@RequestMapping("/api/limit")
public class LimitController {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();
//    @Autowired
//    private WebSocketServer webSocket;
    /**
     * 测试限流注解，下面配置说明该接口 60秒内最多只能访问 10次，保存到redis的键名为 limit_test，
     */
    @GetMapping
    @Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit")
    public int testLimit() {
        return ATOMIC_INTEGER.incrementAndGet();
    }

    @GetMapping("/testSentinel")
    public @ResponseBody
    String testSentinel() {
        String resourceName = "testSentinel";
        Entry entry = null;
        String retVal;
        try{
            entry = SphU.entry(resourceName, EntryType.IN);
            retVal = "passed";
            log.info("passed");
        }catch(BlockException e){
            retVal = "blocked";
            log.info("blocked");
        }finally {
            if(entry!=null){
                entry.exit();
            }
        }
        return retVal;
    }

    /**
     * 测试websocket
     * @return
     */
    @RequestMapping("/websocket")
    public @ResponseBody String websocket(String s) {
//        try {
////            webSocket.sendtoUser(s,s);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return s;
    }


    RateLimiter limiter = RateLimiter.create(0.1);
    @RequestMapping("/testAcquire")
    public  String testAcquire() {
        System.out.println(limiter.getRate());
        long timeOut = (long) 1;
        boolean isValid = limiter.tryAcquire(5, TimeUnit.SECONDS);
        if (!isValid) {
            return "短期无法获取令牌";
        }
        return "获取到令牌";
    }
}
